// 保存当前点击的座位 用于兼容 点击后与客户端交互异步的处理
var currentTarget = null,
    // 座位是否可以被点击
    isClick = true,
    //保存行对应关系
    myScroll,
    // 记录top的差值 不同的电影院top值可能不一样
    topDiff = 30,
    // 每个座位的高度
    SEAT_HEIGHT = 30,
    MAX_SCALE = 1.5,
    // 需要动态计算一次
    MIN_SCALE = 1,
    // 当前缩放比
    CURRENT_SCALE = 1,
    // 当前内容去的宽度   需要动态计算一次
    CONTENT_WIDTH = document.body.clientWidth,
    // 记录左边导航的top值
    leftNavTopVal = [],
    // 记录当前渲染类型 为true则以 行列  否则 定位
    renderIsRow = true,
    // 记录第一个元素
    firstMap = null,
    // 当前主要内容区的基本高度
    maxContentHeight = 0;

ICONS = {
    '1': 'https://assets.goodsogood.com/static/movie-taobao/seat.png',     // 默认
    '0': 'https://assets.goodsogood.com/static/movie-taobao/seat-buyed.png',    // 已购买
    '2': 'https://assets.goodsogood.com/static/movie-taobao/seat-selected.png',        // 已选
},
    // 记录最大行
    maxRow = 1,
    // 记录醉大列
    maxCol = 1,
    // 已选择的座位
    seatSelectArr = [],
    SeatsDom = document.querySelector( '#container' ),
    ScaleDom = document.querySelector( '.scale' ),
    MapIndexDom = document.querySelector( '#mapIndex' ),
    // 定时器监听
    timer = null;


function isPassive() {
    var supportsPassiveOption = false;
    try {
        addEventListener( "test", null, Object.defineProperty( {}, 'passive', {
            get: function () {
                supportsPassiveOption = true;
            }
        } ) );
    } catch ( e ) {
    }
    return supportsPassiveOption;
}


// 刷新左侧座位排的位置 和 缩放
function updateLeftMap( isInit, isPinch ) {
    if ( isInit ) {
        var top;

        top = (firstMap.offsetTop - topDiff / 2) * CURRENT_SCALE;

        MapIndexDom.style.cssText = "transform:translate(10px," + top + "px) scale(" + CURRENT_SCALE + ");height:" + (maxContentHeight + topDiff) + "px";

    } else {
        var translate = ScaleDom.style.webkitTransform.match( /translate\(.*?\)/g )[ 0 ];

        // 获得xy值
        translate = translate.replace( /\s|translate|\(|\)|px/g, '' ).split( ',' );

        // 当前换算后的top值
        var _t = (Number( translate[ 1 ] ) + ((topDiff + 6) * CURRENT_SCALE));

        if ( isPinch ) {
            var scale = ScaleDom.style.webkitTransform.match( /scale\(.*?\)/g )[ 0 ];
            scale = scale.replace( /\s|scale|\(|\)/g, '' );

            if ( scale > MAX_SCALE ) scale = MAX_SCALE;

            CURRENT_SCALE = scale;

            var height = maxRow * SEAT_HEIGHT < 300 ? 300 : maxRow * SEAT_HEIGHT;

            ScaleDom.style.height = SeatsDom.style.height = (height + (CURRENT_SCALE>1?90:120) / MIN_SCALE ) + 'px';
        }

        MapIndexDom.style.cssText = "transform:translate(10px," + _t + "px) scale(" + CURRENT_SCALE + ");height:" + (maxContentHeight + topDiff) + "px";
    }
}

// 启动监听事（缩放或者定位改变）件
function listenChange( isPinch ) {
    // 是否是缩放
    if ( isPinch ) {
        timer = setInterval( function () {
            updateLeftMap( false, true );
        }, 1 )
    } else {
        timer = setInterval( function () {
            updateLeftMap( false );
        }, 1 )
    }
}

// 取消事件监听
function unListenChange() {
    clearInterval( timer );
}

// 座位上一次的top值
var beforeTop = 0;

// 创建座位
function createChildMap( item, isRowAndCol, index, loversItem ) {
    const items = loversItem ? [ item, loversItem ] : item;

    var span = document.createElement( 'span' ),
        current_ic = ICONS[ item.status ],

        x = isRowAndCol ? item.column * SEAT_HEIGHT : item.left_px,
        y = isRowAndCol ? item.row * SEAT_HEIGHT : item.top_px;

    if ( beforeTop !== y ) {
        leftNavTopVal.push( {
            val: y,
            name: item.row_name,
        } );
        beforeTop = y;
    }

    var styles = "position:absolute;width:20px;height:20px;background:url(" + current_ic + ") center;background-size:cover;left:" + x + "px;top:" + y + "px;";

    if ( item.flag === 1 ) {
        styles += 'transform:scale(1.25);transform-origin:left center';
    } else if ( item.flag === 2 ) {
        styles += 'transform:scale(1.25);transform-origin:right center';
    }

    span.style.cssText = styles;
    span.id = "map-" + item.ext_id;

    span.status = item.status;

    // 本地维护一个当前已选择座位的数组
    if ( item.status === 2 ) seatSelectArr.push( item );

    span.addEventListener( 'click', function ( ev ) {
        if ( !isClick ) return;

        switch ( this.status ) {
            case 0:
                return;
            case 1:

                currentTarget = items;
                isClick = false;

                window.postMessage( JSON.stringify( { isSelect: 1, items:items } ) );

                return;
            case 2:
                currentTarget = items;
                isClick = false;
                window.postMessage( JSON.stringify( { isSelect: 0, items:items } ) )
        }
    }, false )

    if ( index === 0 ) firstMap = span;

    SeatsDom.appendChild( span );
}

function isArray( o ) {
    return Object.prototype.toString.call( o ) == '[object Array]';
}

// 点击座位的回调取消
function clickSeatFn( data ) {
    var _id = data.isSelect === 1 ? 2 : 1;
    if ( data.isOk === 1 ) {
        if ( !isArray( currentTarget ) ) currentTarget = [ currentTarget ];

        for ( let i = currentTarget.length - 1; i >= 0; i-- ) {
            let _tg = document.querySelector( '#map-' + currentTarget[ i ].ext_id );

            _tg.status = _id;
            _tg.style.background = 'url(' + ICONS[ _id ] + ')';
            _tg.style.backgroundSize = 'cover';
        }
    }

    isClick = true;
    currentTarget = null;
}

function closeSeatSelect( ids ) {
    if ( !isArray( ids ) ) ids = [ ids ];

    for ( let i = ids.length - 1; i >= 0; i-- ) {
        var _rm = document.querySelector( '#map-' + ids[ i ] );

        _rm.status = 1;
        _rm.style.background = 'url(' + ICONS[ 1 ] + ')';
        _rm.style.backgroundSize = 'cover';
    }

}

// 渲染左测的座位排号
function createMapIndex() {
    for ( var i = 0; i < leftNavTopVal.length; i++ ) {
        var span = document.createElement( 'span' );

        span.innerHTML = leftNavTopVal[ i ].name;
        span.style.top = (leftNavTopVal[ i ].val - topDiff) + 'px';

        MapIndexDom.appendChild( span );
    }

}

// 绑定所有交互事件
function bindEventTouch( contWidth ) {

    var width = CONTENT_WIDTH = contWidth,
        height = maxRow * SEAT_HEIGHT < 300 ? 300 : maxRow * SEAT_HEIGHT;

    CURRENT_SCALE = MIN_SCALE = document.body.clientWidth / width;


    ScaleDom.style.width = SeatsDom.style.width = width + 'px';
    ScaleDom.style.height = SeatsDom.style.height = (height + 100 / MIN_SCALE ) + 'px';

    myScroll = new IScroll( '.wraper', {
        zoom: true,
        scrollX: true,
        scrollY: true,
        scrollbars: false,
        listenX: true,
        listenY: true,
        wheelAction: 'zoom',
        zoomMax: MAX_SCALE,
        zoomMin: MIN_SCALE,
        startZoom: MIN_SCALE,
        disablePointer: true,
        disableTouch: false,
        click: true,
        tap: true,
    } );
    //document.querySelector('#CCC').innerHTML = document.body.clientWidth + '---'+ document.body.clientHeight;
    myScroll.zoom( MIN_SCALE, document.body.clientWidth/2, document.body.clientHeight/2, 0 );

    // 滑动开始
    myScroll.on( 'scrollStart', function () {
        listenChange();
    } )

    // 滑动结束
    myScroll.on( 'scrollEnd', function () {
        unListenChange();
        myScroll.refresh();
    } )
    // 滑动开始
    myScroll.on( 'zoomStart', function () {
        unListenChange();
        listenChange( true );
    } )
    // 滑动结束
    myScroll.on( 'zoomEnd', function () {
        unListenChange( true );
        // 修正一次top值
        updateLeftMap( false, true );
        myScroll.refresh();
    } )


    // 绑定双击事件
    var dbClick = new Hammer( document.querySelector( '#eventClick' ) );

    // 绑定默认事件
    document.addEventListener( 'touchmove', function ( e ) {
        e.preventDefault();
    }, isPassive() ? {
        capture: false,
        passive: false
    } : false );

    document.addEventListener( 'touchend', function ( e ) {
        addAnimation( '#mapIndex' );
    }, false );


    dbClick.on( 'tap', function ( ev ) {
        /* if ( !isFirst ) return;
         isFirst = false;*/

        addAnimation( '.scale' );

        var targetScale = 1.3;

        myScroll.zoom( targetScale, ev.center.x, ev.center.y, 500 );

        CURRENT_SCALE = targetScale;

        updateLeftMap( false, true );

    } );
}

// 计算最近观影区
function calcGoodMap() {

    var _dm = document.querySelector( '#mainCenter' ),
        // 渲染最大列
        _col = Math.ceil( maxCol / 3 ),
        //渲染最大行
        _row = Math.ceil( maxRow / 3 ),
        // 计算最大高宽度
        _maxWidth = _col * 22 + 28,
        _maxHeight = (_row * topDiff + 28) * CURRENT_SCALE,
        // 计算定位的位置
        posX = (Math.round( (maxCol - _col) / 2 ) * 22 - 5),
        posY = Math.round( (maxRow - _row) / 2 ) * topDiff - 5;

    console.log( (Math.round( (maxCol - _col) / 2 ) ), CURRENT_SCALE )
    console.log( _row )

    _dm.style.cssText = "width:" + _maxWidth + "px;height:" + _maxHeight + "px;left:" + posX + "px;top:" + posY + "px";
}

// 添加一次动画
function addAnimation( target ) {
    var _sc = document.querySelector( target ).className;
    document.querySelector( target ).className += ' transform';
    setTimeout( function () {
        document.querySelector( target ).className = _sc.replace( ' transform', '' );
    }, 600 );
}

function init( seatData ) {
    var minFirstLeft = 50,
        lastSeat = null;

    document.querySelector( '.wraper' ).style.width = document.body.clientWidth + 'px';

    for ( var i = 0; i <= seatData.seats.seat.length - 1; i++ ) {
        var _mp = seatData.seats.seat[ i ];

        minFirstLeft = seatData.regular ? seatData.min_row * 30 : seatData.min_left_px;
        // seatData.regular  为true 使用行列  为false 使用坐标

        if ( _mp.flag === 1 ) {
            createChildMap( _mp, seatData.regular, i, seatData.seats.seat[ i + 1 ] );
        } else if ( _mp.flag === 2 ) {
            createChildMap( _mp, seatData.regular, i, seatData.seats.seat[ i - 1 ] );
        } else {
            createChildMap( _mp, seatData.regular, i );
        }

        // 记录top差值
        if ( i === 0 ) {
            topDiff = seatData.regular ? 30 : _mp.top_px;
        }

        // 记录最后一个元素
        if ( i === seatData.seats.seat.length - 1 ) lastSeat = _mp;


    }

    renderIsRow = seatData.regular;

    // 计算行列最大值
    maxCol = seatData.regular ? seatData.max_column : (Math.floor( (seatData.max_left_px - seatData.min_left_px) / 22 )) + 1;
    maxRow = leftNavTopVal.length;

    maxContentHeight = seatData.regular ? seatData.max_row * SEAT_HEIGHT : seatData.max_top_px - seatData.min_top_px;
    maxContentWidth = seatData.regular ? seatData.max_column * 31 + topDiff : seatData.max_left_px - seatData.min_left_px + 18 + minFirstLeft * 2;

    //document.querySelector( '#CCC' ).innerHTML = seatData.regular
    // 绑定主要缩放滑动事件
    bindEventTouch( maxContentWidth /*|| maxCol * SEAT_HEIGHT + minFirstLeft*/ );

    // 初始化左侧定位值
    updateLeftMap( false );
    // 渲染左边导航
    createMapIndex();
    // 计算最佳位置
    //calcGoodMap();

    /* var hammertime2 = new Hammer( document.querySelector( '#CCC' ) );
     hammertime2.on( 'tap', function () {
         window.location.reload();
     } )*/
}

// 获取RN发送的数据
document.addEventListener( 'message', function ( e ) {
    var data = JSON.parse( e.data );
    switch ( data.event ) {
        case 'INIT':
            init( data.data );
            break;
        case 'CLICK_SEAT':
            // 选座验证
            clickSeatFn( data.data );
            break;
        case 'CLOSE_SEAT':
            // 取消选座
            closeSeatSelect( data.data );

    }
} );
